<?php
class SP_Controller_Page
{
	protected $module;
	protected $content;
	protected $page_content;
	
	public function sendHeader()
	{
		header('Content-Type: text/html; charset='.SP_Config::get('app')->encoding); 
	}
	
	public function setModule($value)
	{
		$this->module=$value;
		$this->module->setPage($this);
	}
	
	public function renderModule()
	{
		if( !$_module__=$this->module ) throw new excepton('Module not setted in page controller');
		$_module__->execute();
		extract($_module__->getVars());
		ob_start();
		include($_module__->getViewFile());
		$this->content=ob_get_contents();
		ob_end_clean();
	}
	
	protected function getTemplatePath()
	{
		$name = $this->template? $this->template : SP_Config::get('app')->template;
		$name.='.php';
		if( SP_Path::isFile(SP_Config::get('system_app')->templates_dir.'/'.$name, 'module') )
		{
			$out=SP_Path::get('module').SP_Config::get('system_app')->templates_dir.'/'.$name;
		}
		elseif( SP_Path::isFile($name, 'app_templates') )
		{
			$out=SP_Path::get('app_templates').$name;
		}
		else
		{
			throw new exception("Template '$this->template' not found");
		}
		return $out;
	}
	
	public function render()
	{
		$templ=$this->getTemplatePath();
		ob_start();
		include($templ);
		$this->page_content=ob_get_contents();
		ob_end_clean();
	}
	
	public function show()
	{
		$this->sendHeader();
		
		echo $this->page_content;
	}
	
		/***SLOTS***/
	
	public function setSlot($name,$slot)
	{
		$this->slots[$name]=$slot;
	}
	
	public function hasSlot($name)
	{
		return isset($this->slots[$name]);
	}
	
	public function slot($name, $alt=NULL)
	{
		if ($this->hasSlot($name))
		{
			return $this->slots[$name];
		}
		else
		{
			return $alt;
		}
	}
	
	public function setTemplate($value)
	{
		$this->template=$value;
	}
	
	public	function getTemplate()
	{
		return $this->template;
	}
	
	public	function getContent()
	{
		return $this->content;
	}
	
	public	function content()
	{
		echo $this->getContent();
	}
}